package models

import (
	"fmt"
	"strings"

	"gitee.com/sansaniot/ssiot-core/httpmvc/model"
	"gorm.io/datatypes"

	cDto "ssdevice/common/dto"
	"ssdevice/common/utils"
	"ssdevice/internal/device/models/query"
)

type SysDevSystem struct {
	Id         string          `json:"id" gorm:"primaryKey;type:varchar(255);comment:id"`
	DevSn      string          `json:"devSn" gorm:"type:varchar(255);comment:设备序列号"`
	Data       datatypes.JSON  `json:"data" gorm:"type:jsonb;comment:profile.system"`
	CreateTime *cDto.LocalTime `json:"createTime" gorm:"type:timestamptz(6);comment:创建时间"`
	UpdateTime *cDto.LocalTime `json:"updateTime" gorm:"type:timestamptz(6);comment:更新时间"`

	model.Model
}

func (SysDevSystem) TableName() string {
	return "sys_dev_system"
}

func (e *SysDevSystem) Generate() interface{} {
	o := *e
	return &o
}

func (e *SysDevSystem) GetId() interface{} {
	return e.Id
}

func (e *SysDevSystem) FindDevSystem(req *query.SysDevSystemQuery) (err error, one SysDevSystem) {
	err = e.FindOne(&one, cDto.MakeCondition(req.GetNeedSearch()))
	return
}

func (e *SysDevSystem) UpdateDevSystem(sn string, data map[string]interface{}) error {
	path := "{system}"
	dataStr := string(utils.MapToBytes(data))
	sql := "update sys_dev_system set data = jsonb_set(data::jsonb, '" + path + "', jsonb_update(data #> '" + path + "', '" + dataStr + "' :: jsonb ) ) where dev_sn = '%s'"
	// 防止字符串中存在%占位符
	sql = strings.ReplaceAll(sql, "%\"", "%%\"")
	// 防止字符串中存在?占位符
	sql = fmt.Sprintf(sql, sn)
	return e.Orm.Raw(sql).Scan(e).Error
}
